package simpleHttpClient;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * this a utility class that help to achieve advanced function of this project
 * it can loop through a s specified HTML file to find out all of the http address in it;
 * @author Li Weihan
 * Scott Wendlandt
 * Rebecca Chandler
 * @version 1.5
 *
 */
public class Utilities {

	/**
	 * this class will go through the file parameter and find out all of the url address, and use them to generate a list of Request,
	 * sort the list based the host name of the url and return it; 
	 * @param file the file that will  loop through;
	 * @return return the sorted list of Request
	 */

	public  Request[] loopURL(File file){
		String content="";
		FileInputStream reader=null;
		try {
			reader = new FileInputStream(file);
			int data;   
			while ((data = reader.read()) != -1) {  
				content += (char) data;  
			}   
		} catch (FileNotFoundException e) {
			System.out.println("file not exit");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("unable to read file");
			e.printStackTrace();
		} finally{
			if(reader!=null){
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		//content.replace("\"/", user.getHostName()+'/');
		ArrayList<Request> url=new ArrayList<Request>();
		Pattern pattern = Pattern.compile("(?<=href=\").*?(?=\")",Pattern.CASE_INSENSITIVE );   
		Matcher matcher = pattern.matcher(content);
		Request request;
		while(matcher.find()){
			request = new Request(matcher.group());
			request.setConnectionClose(false);
			url.add(request);
		}

		return sortURL(url);
	}
	/**
	 * this is a helper class that sort the Request list based on their host name
	 * @param aim the unsorted Request list
	 * @return the sorted Request list
	 */
	private Request[] sortURL (ArrayList<Request> aim){
		Comparator<Request> urlCompare = new URLComparator();
		Collections.sort(aim, urlCompare);
		Request[] retVal= new Request[aim.size()];
		return aim.toArray(retVal);

	}
}